package com.bg.sparkproject.pattern.proxy.dynamic;

import com.bg.sparkproject.pattern.proxy.BuyHosue;
import com.bg.sparkproject.pattern.proxy.statics.BuyHosueImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Auther: zhengshunzhi
 * @Date: 2019/1/4 11:56
 * @Description: 动态代理工厂类
 */
public class DynamicProxyFactory {

    private Object target;

    public DynamicProxyFactory(final Object target) {
        this.target = target;
    }

    public <T> T getProxyInstance() {
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("买房前准备");
                Object result = method.invoke(target, args);
                System.out.println("买房后装修");
                return result;
            }
        });
    }

    public static void main(String[] args) {
        BuyHosueImpl target = new BuyHosueImpl();
        System.out.println(target.getClass());
        BuyHosue buyHosue = (BuyHosue) new DynamicProxyFactory(target).getProxyInstance();
        System.out.println(buyHosue.getClass());
        buyHosue.buyHosue();
    }
}
